﻿using System;
using MongoDB.Driver.Builders;
using NetFluid;
using Sito.Model;

namespace Sito.Logic
{
    internal class UserManager : FluidPage
    {
        [Route("signin")]
        public void SignIn(string mail, string password)
        {
            if (mail == null || password == null)
            {
                render("Sito.View.Signin");
                return;
            }

            foreach (User user in Database.User.Find(Query.EQ("Mail", mail)))
            {
                if (user.Password == password)
                {
                    session("User", user);

                    ResponseHeaders.Add("Location", "/");
                    ResponseCode = StatusCode.Found;
                    return;
                }
            }
            render("Sito.View.Signin", "wrong mail or password");
        }

        [Route("signup")]
        public void SignUp(string username, string password, string mail)
        {
            if (username==null || mail == null || password == null)
            {
                render("Sito.View.Signup");
                return;
            }

            var user = new User
                           {
                               LastAccess = DateTime.Now,
                               LastIP = RemoteIP,
                               Mail = mail,
                               NiceName = username,
                               Password = password,
                               SignupDate = DateTime.Now,
                               SignupIP = RemoteIP,
                               Status = User.UserStatus.Active
                           };
            Database.User.Save(user);

            ResponseHeaders.Add("Location", "/");
            ResponseCode = StatusCode.Found;
        }
    }
}